import axios from 'axios'
import Msger from '@/utils/msg'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import CryptoJS from 'crypto-js'
import { getToken, getLanguage } from '@/utils/cookies'
import { REQ_SUCCESS_CODE } from '@/constant/global'
import store from '@/store/index'
import { randomWord, urlSateBase64Encode } from '@/utils/index'

const service = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? process.env.VUE_APP_BASE_API
      : '/api',
  timeout: 40000,
  withCredentials: true // send cookies when cross-domain requests
})
const tokenWhiteList = ['/login', '/auth/oauth/token']
// Request interceptors
service.interceptors.request.use(
  (config: any) => {
    const params: any = {
      platform: '2',
      timestamp: new Date().getTime(),
      nonce: randomWord(false, 16, 0)
    }
    if (localStorage.getItem('sid')) {
      config.headers.sid = localStorage.getItem('sid')
      params.sid = localStorage.getItem('sid')
    }
    const keyList = Object.keys(params)
    console.log(keyList.sort())
    const strList: any = []
    keyList.sort().forEach((key, index) => {
      strList[index] = `${key}=${params[key]}`
    })
    const signatureStr = CryptoJS.HmacSHA256(strList.join('&'), 'xNGoL2GE')
    const base64String = CryptoJS.enc.Base64.stringify(signatureStr)
    config.headers.signature = urlSateBase64Encode(base64String)
    config.headers.timestamp = params.timestamp
    config.headers.nonce = params.nonce
    config.headers.platform = params.platform
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// Response interceptors
const msgWhiteList = [
  '/auth/oauth/token',
  '/order/v2/api-docs',
  '/product/productApplyAudit/exportMyProductApplyAudits'
]
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(response)
    if (!msgWhiteList.includes(response.config.url as any)) {
      if (res.code !== REQ_SUCCESS_CODE) {
        Msger.error(`Error Message: ${res.msg} Code: ${res.code}`)
        return response.data
      }
    }
    return response.data
  },
  error => {
    let cb: any = () => {
      // 注释
    }
    if (error && error.response) {
      const status = error.response.status + ''
      const errCb: any = {
        401: () => {
          // if (router.app.$route.path === '/login') return
          // db.clear()
          // UserModule.LogOut()
          // router.push(`/login?redirect=${router.app.$route.fullPath}`)
        }
      }
      cb = errCb[status]
    }
    Msger.reqerror(error, '未知错误，请稍后重试')
    cb && cb()
    return Promise.reject(error)
  }
)

export default service
